package org.linuxsogood.boot.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author honway.liu
 * @date 2019/12/5 10:01 下午
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 */
@Slf4j
public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("客户端地址:{}", ctx.channel().remoteAddress());
        ByteBuf buf = (ByteBuf) msg;
        log.info("接收到客户端发过来的消息: {}", buf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("消息读取完毕, 回复消息给客户端");
        ctx.writeAndFlush(Unpooled.copiedBuffer("server 端收到了你的消息", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("server 端发生异常", cause);
        ctx.close();
    }
}
